<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧分类树 -->
      <el-col :span="6">
        <div class="category-tree">
          <div class="tree-header">
            <span>商品类别</span>
            <el-button
              type="primary"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['procurementmanagement:category:add']"
            >新增</el-button>
          </div>
          <el-tree
            :data="categoryTree"
            :props="defaultProps"
            node-key="categoryId"
            highlight-current
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  @click.stop="() => handleUpdate(data)"
                  v-hasPermi="['procurementmanagement:category:edit']"
                >修改</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click.stop="() => handleDelete(data)"
                  v-hasPermi="['procurementmanagement:category:remove']"
                >删除</el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧商品列表 -->
      <el-col :span="18">
        <div class="goods-list">
          <el-form :model="goodsQueryParams" ref="goodsQueryForm" size="small" :inline="true">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="goodsQueryParams.name"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter.native="handleGoodsQuery"
              />
            </el-form-item>
            <el-form-item label="商品编号" prop="sn">
              <el-input
                v-model="goodsQueryParams.sn"
                placeholder="请输入商品编号"
                clearable
                @keyup.enter.native="handleGoodsQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGoodsQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetGoodsQuery">重置</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handleGoodsAdd"
                v-hasPermi="['procurementmanagement:goods:add']"
              >新增</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="goodsLoading" :data="goodsList">
            <el-table-column label="商品名称" align="center" prop="name" />
            <el-table-column label="商品编号" align="center" prop="sn" />
            <el-table-column label="商品类别" align="center" prop="categoryName" />
            <el-table-column label="品牌" align="center" prop="brandName" />
            <el-table-column label="销售价格" align="center" prop="price">
              <template slot-scope="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column label="商品标签" align="center" prop="labelNames" />
            <el-table-column label="状态" align="center" prop="marketEnable">
              <template slot-scope="scope">
                {{ scope.row.marketEnable === 1 ? '上架' : '下架' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleGoodsUpdate(scope.row)"
                  v-hasPermi="['procurementmanagement:goods:edit']"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleGoodsDelete(scope.row)"
                  v-hasPermi="['procurementmanagement:goods:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="goodsTotal>0"
            :total="goodsTotal"
            :page.sync="goodsQueryParams.pageNum"
            :limit.sync="goodsQueryParams.pageSize"
            @pagination="getGoodsList"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级类别名称" prop="parentId">
          <el-cascader
            v-model="form.parentId"
            :options="categoryTree"
            :props="cascaderProps"
            placeholder="请选择"
            style="width: 100%"
            clearable
          ></el-cascader>
        </el-form-item>

        <el-form-item label="商品类别名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="商品类别编号" prop="customSn">
          <el-input
            v-model="form.customSn"
            placeholder="系统自动生成"
            readonly
          />
        </el-form-item>

        <el-form-item label="分类排序" prop="categoryOrder">
          <el-input-number
            v-model="form.categoryOrder"
            controls-position="right"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio label="YES">是</el-radio>
            <el-radio label="NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 商品编辑对话框 -->
    <el-dialog :title="goodsFormTitle" :visible.sync="goodsDialogVisible" width="800px" append-to-body>
      <el-form :model="goodsForm" label-width="120px" :rules="goodsRules" ref="goodsFormRef">
        <el-form-item label="商品名称" prop="productName" required>
          <el-input v-model="goodsForm.productName"></el-input>
        </el-form-item>
        <el-form-item label="商品编号" prop="productCode">
          <el-input v-model="goodsForm.productCode" placeholder="系统自动生成" readonly></el-input>
        </el-form-item>
        <el-form-item label="商品类别" prop="productCategory" required>
          <el-cascader
            v-model="goodsForm.productCategory"
            :options="categoryOptions"
            :props="cascaderProps"
            placeholder="请选择商品类别"
            style="width: 100%"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="品牌" prop="productBrand">
          <el-select
            v-model="goodsForm.productBrand"
            placeholder="请选择品牌"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="brand in brandOptions"
              :key="brand.brandId"
              :label="brand.name"
              :value="brand.brandId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品标签" prop="labels">
          <el-select
            v-model="goodsForm.labels"
            multiple
            filterable
            placeholder="请选择商品标签"
            style="width: 100%"
          >
            <el-option
              v-for="label in labelOptions"
              :key="label.id"
              :label="label.name"
              :value="label.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品规格" prop="specifications">
          <el-select
            v-model="goodsForm.specifications"
            multiple
            placeholder="请选择商品规格"
            style="width: 100%"
            clearable
          >
            <el-option-group
              v-for="spec in specOptions"
              :key="spec.specId"
              :label="spec.specName"
            >
              <el-option
                v-for="value in spec.values || []"
                :key="value.specValueId"
                :label="value.specValue"
                :value="value.specValueId"
              >
                <span style="float: left">{{ value.specValue }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                         {{ spec.specName }}
                       </span>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status" required>
          <el-radio-group
            v-model="goodsForm.status"
            @focus.native="handleRadioFocus"
          >
            <el-radio label="上架">上架</el-radio>
            <el-radio label="下架">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品图片">
          <div v-if="Array.isArray(goodsForm.image) && goodsForm.image.length > 0" class="image-preview">
            <div v-for="(image, index) in goodsForm.image" :key="index" class="image-item">
              <el-image
                style="width: 100px; height: 100px"
                :src="image.url || image"
                fit="cover"
                :preview-src-list="getPreviewSrcList(goodsForm.image)"
              >
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </div>

          <el-upload
            ref="upload"
            :on-remove="handleRemove"
            list-type="picture-card"
            :file-list="fileList"
            :on-change="handleFileChange"
            :auto-upload="false"
            action="#"
            :http-request="handleUploadRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传jpg, jpeg, png格式，建议分辨率不要超过800*800，大小不超过3M的1:1正方形图片</div>
          </el-upload>
          <el-button @click="submitUpload">上传</el-button>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="销售价格(¥)" prop="salesPrice">
              <el-input-number v-model="skuForm.salesPrice" :min="0" :precision="2" controls-position="right" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="零售价格(¥)" prop="retailPrice">
              <el-input-number v-model="skuForm.retailPrice" :min="0" :precision="2" controls-position="right" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="成本价格(¥)" prop="costPrice">
              <el-input-number v-model="skuForm.costPrice" :min="0" :precision="2" controls-position="right" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="市场价(¥)" prop="marketPrice">
              <el-input-number v-model="skuForm.marketPrice" :min="0" :precision="2" controls-position="right" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="税率(%)" prop="taxRate">
              <el-input-number
                v-model="skuForm.taxRatePercent"
                :min="0"
                :max="100"
                :precision="2"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitGoodsForm">保存</el-button>
          <el-button @click="goodsDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, addCategory, updateCategory, delCategory, listGoodsByCategories } from "@/api/goods/category";
import { listGoods, delGoods, addGoods, getGoods, updateGoods } from "@/api/goods/goods";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listValues, getValues, delValues, addValues, updateValues } from "@/api/goods/values";
import { listSpecification } from "@/api/procurementmanagement/specification";

import { listLabel, getGoodsLabels, updateGoodsLabels } from "@/api/goods/label";
import { listBrand } from "@/api/goods/brand";
import OSS from 'ali-oss';

export default {
  name: "Category",
  data() {
    return {
      specOptions: [],
      selectedSpecValues: [],
      // 分类树数据
      categoryTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      // 添加标签选项数据
      labelOptions: [],
      // 修改goodsForm，添加labels属性
      goodsForm: {
        id: '',
        productName: '',
        productCode: '', // 移除required验证
        productCategory: '',
        productBrand: '',
        labels: [],
        specifications: [],
        status: '上架',
        image: []
      },
      // 商品列表相关
      goodsList: [],
      goodsLoading: false,
      goodsTotal: 0,
      goodsQueryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        name: null,
        sn: null
      },
      cascaderProps: {
        value: 'categoryId',
        label: 'name',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      components: {
        Treeselect
      },
      // 分类对话框相关
      open: false,
      title: "",
      form: {
        categoryId: null,
        parentId: null,
        name: null,
        customSn: '',  // 新增的编号字段
        categoryOrder: 0,
        isShow: "YES"
      },
      rules: {
        name: [{required: true, message: "分类名称不能为空", trigger: "blur"}]
      },

      // 商品表单相关
      goodsDialogVisible: false,
      goodsFormTitle: '',
      goodsRules: {
        productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        productCategory: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
        status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
        // 移除productCode的验证规则
      },
      fileList: [],
      categoryOptions: [],
      brandOptions: [],
      ossClient: null,
      skuForm: {
        salesPrice: 0,    // 销售价格
        retailPrice: 0,   // 零售价格
        costPrice: 0,     // 成本价格
        marketPrice: 0,   // 市场价
        taxRate: 0,       // 税率
        taxRatePercent: 0 // 直接存储百分比数字
      }
    };
  },
  created() {
    this.initOSSClient();
    this.getCategoryTree();
    this.getAllGoods();
    this.fetchCategoryOptions();
    this.fetchBrandOptions();
    this.fetchSpecifications();
    // 初始化时获取标签列表
    this.fetchLabelOptions();
  },
  computed: {
    taxRateDecimal() {
      return this.skuForm.taxRatePercent / 100;
    }
  },
  methods: {
    handleGoodsAdd() {
      this.resetGoodsForm();
      this.goodsDialogVisible = true;
      this.goodsFormTitle = "添加商品";
    },
        this.resetGoodsForm();
        this.goodsDialogVisible = true;
        this.goodsFormTitle = "添加商品";
      },
    async fetchLabelOptions() {
      try {
        const response = await listLabel(); // 直接使用导入的API方法
        this.labelOptions = response.rows || [];
      } catch (error) {
        console.error('获取标签列表失败:', error);
        this.$message.error('获取标签列表失败');
      }
    },
    async fetchSpecifications() {
      try {
        const specRes = await listSpecification();
        const specs = specRes.rows || [];

        this.specOptions = await Promise.all(specs.map(async spec => {
          const valuesRes = await listValues({ specId: spec.specId });
          return {
            ...spec,
            values: valuesRes.rows || []
          };
        }));
      } catch (error) {
        console.error('获取规格列表失败:', error);
        this.$message.error('获取规格列表失败');
      }
    },
    handleRadioFocus(e) {
      // 移除所有radio的aria-hidden属性
      const radioInputs = document.querySelectorAll('.el-radio__original');
      radioInputs.forEach(input => {
        input.removeAttribute('aria-hidden');
      });
    },
    getPreviewSrcList(images) {
      if (!images) return [];
      return Array.isArray(images)
        ? images.map(img => img.url || img)
        : [images];
    },
    // 获取某个节点及其所有子节点的ID
    getAllChildCategoryIds(node) {
      let ids = [node.categoryId];
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          ids = ids.concat(this.getAllChildCategoryIds(child));
        });
      }
      return ids;
    },
    normalizer(node) {
      return {
        id: node.categoryId,
        label: node.name,
        children: node.children
      };
    },
    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        categoryId: null,
        parentId: null,
        name: null,
        categoryOrder: 0,
        isShow: "YES"
      };
    },
    /** 获取分类树 */
    getCategoryTree() {
      listCategory().then(response => {
        console.log('分类树数据:', response.rows);
        this.categoryTree = this.buildTree(response.rows);
      });
    },

    /** 构建树形结构 */
    buildTree(data) {
      const map = {};
      const result = [];

      data.forEach(item => {
        map[item.categoryId] = {
          ...item,
          children: [],
          disabled: item.categoryId === this.form.categoryId // 禁止选择自己作为父级
        };
      });

      data.forEach(item => {
        const parent = map[item.parentId];
        if (parent) {
          parent.children.push(map[item.categoryId]);
        } else {
          result.push(map[item.categoryId]);
        }
      });

      return result;
    },

    // 分类节点点击事件
    handleNodeClick(data) {
      // 获取当前节点及其所有子节点的ID
      const categoryIds = this.getAllChildCategoryIds(data);

      this.goodsQueryParams = {
        ...this.goodsQueryParams,
        categoryIds: categoryIds.join(','), // 传递多个分类ID
        pageNum: 1
      };

      this.getGoodsList();
    },

    // 新增方法：获取所有商品
    getAllGoods() {
      this.goodsLoading = true;
      this.goodsQueryParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        name: null,
        sn: null,
        categoryIds: null // 确保清空分类IDs
      };

      listGoods({
        pageNum: 1,
        pageSize: 10
      }).then(response => {
        this.goodsList = response.rows;
        this.goodsTotal = response.total;
        this.goodsLoading = false;
      }).catch(() => {
        this.goodsLoading = false;
      });
    },

    // 获取商品列表
    getGoodsList() {
      this.goodsLoading = true;

      // 如果有多个分类ID，使用新的API
      if (this.goodsQueryParams.categoryIds) {
        listGoodsByCategories(this.goodsQueryParams.categoryIds)
          .then(response => {
            this.goodsList = response.rows;
            this.goodsTotal = response.total;
            this.goodsLoading = false;
          })
          .catch(() => {
            this.goodsLoading = false;
          });
      } else {
        // 原来的查询逻辑
        const params = {
          pageNum: this.goodsQueryParams.pageNum,
          pageSize: this.goodsQueryParams.pageSize,
          name: this.goodsQueryParams.name || undefined,
          sn: this.goodsQueryParams.sn || undefined,
          categoryId: this.goodsQueryParams.categoryId || undefined
        };

        listGoods(params).then(response => {
          this.goodsList = response.rows;
          this.goodsTotal = response.total;
          this.goodsLoading = false;
        }).catch(() => {
          this.goodsLoading = false;
        });
      }
    },

    /** 商品搜索 */
    handleGoodsQuery() {
      this.goodsQueryParams.pageNum = 1;
      this.getGoodsList();
    },

    /** 重置商品搜索 */
    resetGoodsQuery() {
      this.resetForm("goodsQueryForm");
      this.handleGoodsQuery();
    },

    // 其他原有方法保持不变
    handleAdd() {
      this.reset();
      // 生成自动编号 CY+年月日+时分秒
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      this.form.customSn = `CY${year}${month}${day}${hours}${minutes}${seconds}`;
      this.open = true;
      this.title = "添加商品分类";
    },

    handleUpdate(row) {
      this.reset();
      const categoryId = row.categoryId;
      getCategory(categoryId).then(response => {
        this.form = response.data;
        // 重新构建树，禁用当前分类
        this.getCategoryTree();
        this.open = true;
        this.title = "修改商品分类";
      });
    },

    handleDelete(row) {
      const categoryId = row.categoryId;
      this.$modal.confirm('是否确认删除商品分类编号为"' + categoryId + '"的数据项？').then(() => {
        return delCategory(categoryId);
      }).then(() => {
        this.getCategoryTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getCategoryTree(); // 重新获取分类树
              this.fetchCategoryOptions(); // 重新获取分类选项
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getCategoryTree(); // 重新获取分类树
              this.fetchCategoryOptions(); // 重新获取分类选项
            });
          }
        }
      });
    },
    handleGoodsDelete(row) {
      this.$confirm('是否确认删除商品编号为"' + row.id + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delGoods(row.id);
      }).then(response => {
        if (response.code === 200) {
          this.$message.success('删除成功!');
          this.getGoodsList();
        } else {
          throw new Error(response.message || '删除失败');
        }
      }).catch(error => {
        console.error('删除失败:', error);
        this.$message.error(error.message || '删除失败');
      });
    },

    handleGoodsUpdate(row) {
      this.resetGoodsForm();
      this.goodsDialogVisible = true;
      this.goodsFormTitle = "修改商品";
      this.fetchGoodsData(row.id);
    },
    resetGoodsForm() {
      this.goodsForm = {
        id: '',
        productName: '',
        productCode: '',
        productCategory: '',
        productBrand: '',
        specifications: [],
        status: '上架',
        image: []
      };
      this.skuForm = {
        salesPrice: 0,
        retailPrice: 0,
        costPrice: 0,
        marketPrice: 0,
        taxRate: 0,
        taxRatePercent: 0 // 新增这一行
      };
      this.fileList = [];
      // 清除验证状态
      if (this.$refs.goodsFormRef) {
        this.$refs.goodsFormRef.clearValidate();
      }
    },
    // 商品表单相关方法
    async fetchCategoryOptions() {
      try {
        const res = await listCategory();
        this.categoryOptions = this.buildTree(res.rows || []);
        // 确保构建的树形结构正确
        console.log('分类选项:', this.categoryOptions);
      } catch (error) {
        console.error('获取分类列表失败:', error);
        this.$message.error('获取分类列表失败');
      }
    },
    async fetchBrandOptions() {
      try {
        const res = await listBrand({pageSize: 1000});
        this.brandOptions = res.rows || [];
      } catch (error) {
        console.error('获取品牌列表失败:', error);
        this.$message.error('获取品牌列表失败');
      }
    },
    async fetchGoodsData(id) {
      try {
        const res = await getGoods(id);
        const data = res.data;

        // 获取商品标签
        const labelRes = await getGoodsLabels(id);
        const labels = labelRes.data || [];

        // 获取规格值
        const specValueIds = data.specValueIds ? data.specValueIds.split(',') : [];

        let images = [];
        if (data.image) {
          images = Array.isArray(data.image)
            ? data.image
            : data.image.split(',').filter(Boolean).map(url => ({url}));
        }

        this.goodsForm = {
          id: data.id,
          productName: data.name,
          productCode: data.sn,
          productCategory: data.categoryId,
          productBrand: data.brandId || '',
          labels: labels.map(l => l.id),
          specifications: specValueIds,
          status: data.marketEnable === 1 ? '上架' : '下架',
          image: images
        };

        this.skuForm = {
          salesPrice: data.price || 0,
          retailPrice: 0,
          costPrice: data.costPrice || 0,
          marketPrice: data.mktPrice || 0,
          taxRate: data.taxRate || 0,
          taxRatePercent: data.taxRate ? (data.taxRate * 100) : 0
        };

        this.fileList = images.map(img => ({
          name: img.name || '图片',
          url: img.url || img
        }));
      } catch (error) {
        console.error('获取商品详情失败:', error);
        this.$message.error('获取商品详情失败');
      }
    },
    async submitGoodsForm() {
      try {
        // 1. 表单验证
        await this.$refs.goodsFormRef.validate();

        // 2. 准备商品数据
        const goodsData = {
          id: this.goodsForm.id || undefined, // 只有修改时才包含ID
          name: this.goodsForm.productName,
          categoryId: Number(this.goodsForm.productCategory),
          brandId: Number(this.goodsForm.productBrand || 0),
          marketEnable: this.goodsForm.status === '上架' ? 1 : 0,
          price: Number(this.skuForm.salesPrice),
          costPrice: Number(this.skuForm.costPrice),
          mktPrice: Number(this.skuForm.marketPrice),
          taxRate: Number(this.taxRateDecimal),
          image: this.fileList.map(file => file.url).join(','),
          specValueIds: this.goodsForm.specifications.join(',')
        };

        // 3. 提交商品数据
        let response;
        if (this.goodsForm.id) {
          // 修改操作
          response = await updateGoods(goodsData);
        } else {
          // 新增操作
          response = await addGoods(goodsData);
        }

        // 4. 获取商品ID
        const goodsId = response.id || response.data?.id || this.goodsForm.id;
        if (!goodsId) {
          throw new Error('无法获取商品ID，响应数据: ' + JSON.stringify(response));
        }

        // 5. 保存标签关系
        if (this.goodsForm.labels) {
          try {
            await updateGoodsLabels({
              goodsId: goodsId,
              labelIds: this.goodsForm.labels.map(Number)
            });
          } catch (labelError) {
            console.error('标签保存失败:', labelError);
            throw new Error('商品保存成功但标签保存失败: ' + labelError.message);
          }
        }

        this.$message.success(this.goodsForm.id ? '修改成功' : '保存成功');
        this.goodsDialogVisible = false;
        this.getGoodsList();

      } catch (error) {
        console.error('操作失败详情:', {
          error: error.message,
          request: this.goodsForm,
          stack: error.stack
        });
        this.$message.error(`操作失败: ${error.message}`);
      }
    },
    // 保存商品标签关系
    async saveGoodsLabels(goodsId, labelIds) {
      try {
        await updateGoodsLabels({
          goodsId,
          labelIds: labelIds || [] // 确保传入数组，即使为空
        });
      } catch (error) {
        console.error('保存标签关系失败:', error);
        throw error; // 抛出错误让上层处理
      }
    },
    // 图片上传相关方法
    initOSSClient() {
      try {
        this.ossClient = new OSS({
          region: 'oss-cn-shenzhen',
          accessKeyId: 'LTAI5tS35yZTe5jnu1yJpniL',
          accessKeySecret: 'rKET9B5WNRxrGCMSsBJw8ugBqoaWKa',
          bucket: 'magicerp2',
          secure: true,
          endpoint: 'https://oss-cn-shenzhen.aliyuncs.com',
          cname: false
        });
      } catch (error) {
        console.error('OSS初始化失败:', error);
        this.$message.error('OSS服务初始化失败');
      }
    },
    handleFileChange(file, fileList) {
      const uniqueFiles = fileList.reduce((acc, current) => {
        const x = acc.find(item => item.uid === current.uid);
        if (!x) {
          return acc.concat([current]);
        } else {
          return acc;
        }
      }, []);
      this.fileList = uniqueFiles;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleUploadRequest(options) {
      this.handleBeforeUpload(options.file);
    },
    async handleBeforeUpload(file) {
      const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
      if (!validTypes.includes(file.type)) {
        this.$message.error('只能上传JPG/PNG格式的图片!');
        return false;
      }
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error('图片大小不能超过3MB!');
        return false;
      }
      try {
        const fileName = `product-images/${Date.now()}-${file.name.replace(/\s+/g, '-')}`;
        const result = await this.ossClient.put(fileName, file, {
          headers: {'Content-Type': file.type}
        });

        // 更新文件列表
        const newFileObject = {
          uid: file.uid,
          name: file.name,
          url: result.url,
          status: 'success'
        };

        const existingIndex = this.fileList.findIndex(f => f.uid === file.uid);
        if (existingIndex >= 0) {
          this.fileList.splice(existingIndex, 1, newFileObject);
        } else {
          this.fileList.push(newFileObject);
        }

        // 根据后端需要设置goodsForm.image
        // 方案1: 设置为URL字符串
        this.goodsForm.image = this.fileList.map(f => f.url).join(',');

        // 或者方案2: 设置为对象数组
        // this.goodsForm.image = this.fileList.map(f => ({ url: f.url }));

        this.$message.success('图片上传成功');
        return false;
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error(`上传失败: ${error.message}`);
        return false;
      }
    },
    async handleRemove(file, fileList) {
      try {
        await this.$confirm('确定删除这张图片吗?', '提示', {
          type: 'warning'
        });
        this.fileList = fileList;
        this.goodsForm.image = this.fileList.map(f => ({url: f.url}));
        if (file.response && file.response.data && file.response.data.url) {
          try {
            const urlObj = new URL(file.response.data.url);
            const fileName = decodeURIComponent(urlObj.pathname.substring(1));
            await this.ossClient.delete(fileName);
          } catch (ossError) {
            console.warn('OSS删除失败:', ossError);
          }
        }
        this.$message.success('删除成功');
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
        }
      }
    }
  }
};
</script>

<style scoped>
.category-tree {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.goods-list {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
<style scoped>
/* 调整单选按钮样式 */
.el-radio {
  margin-right: 15px;
}

/* 调整表单项间距 */
.el-form-item {
  margin-bottom: 20px;
}

/* 在 style 部分添加 */
.sku-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-divider--horizontal {
  margin: 10px 0 20px 0;
}

.el-select-dropdown__item {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.el-select-group__title {
  padding-left: 10px;
  font-weight: bold;
  color: #333;
}
</style>
